import Vue from 'vue'
import { Module } from 'vuex'
import { SET_QUESTION, SET_QUESTIONS, DEL_QUESTION, CLEAR_QUESTION } from '../mutations'

const question: Module<QuestionInfo, any> = {
  state: {
    QuestionList: [] as Question[],
    PaperName: '',
    LastQuestionId: '',
    QuestionTotalCount: 0,
    RightCount: 0,
    PaperTestHistoryId: '',
  },
  mutations: {
    [SET_QUESTION] (state, { index, question }) {
      let isQuestionFound = false
      if (state.QuestionList[index].QuestionId === question.QuestionId) {
        isQuestionFound = true
      } else if (state.QuestionList[--index].QuestionId === question.QuestionId) {
        isQuestionFound = true
      }
      if (isQuestionFound) {
        Vue.set(state.QuestionList, index, { ...state.QuestionList[index], ...question })
      }
    },
    [DEL_QUESTION] (state, index) {
      const newQuestion = state.QuestionList.map((q, qIndex) => {
        if (qIndex < index) {
          return q
        }
        if (qIndex === index) {
          return null
        }
        if (q.Sequence === 0) {
          return q
        }
        return {
          ...q,
          Sequence: q.Sequence - 1,
        }
      }).filter(q => q)
      console.log(newQuestion.length)
      Vue.set(state, 'QuestionList', newQuestion)
      state.QuestionTotalCount--
    },
    [SET_QUESTIONS] (state, question) {
      Object.assign(state, { RightCount: 0, ...question })
    },
    [CLEAR_QUESTION] (state) {
      Vue.set(state, 'QuestionList', [])
    },
  },
}

export default question
